/**
 * 【动态】日志更新 CQ-YJY-20230720-340【L50】-次世代场景模型：千泊巷
 * 【动态】日志更新 [订单编号] 【[项目名称]】- [订单明细]
 */

const db = require('db');
const moment = require('moment');
const { sendMail } = require('nmailer');

module.exports = async (ctx, next) => {
    const body = ctx.request.body;
    if (ctx.request.body.source !== "order") return await next();

    const order = await getOrder(body); if (!order) return await next();

    send(body, order);

    await next();
}

/** 获取订单数据 */
async function getOrder(body) {
    const { connection, run } = db.init();
    const sqlStr = `
        SELECT orders.*, c.clientName
        FROM orders, client as c
        WHERE 0=0 AND c.id = orders.clientId AND orders.id = ${body.group}
    `
    const result = await run(sqlStr); connection.end();

    if (result.err) {
        return undefined;
    } else {
        return result.rows[0];
    }
}

/** 发邮件 */
async function send(body, order) {

    const tos = [
        'Yellen<yellen@firemonkeysoft.com>',
        '张晓东<zhangxiaodong@firemonkeysoft.com>'
    ];

    order.commercialSpecialistEmail &&
    tos.push(`${order.commercialSpecialistName}<${order.commercialSpecialistEmail}>`);

    order.pmEmail &&
    tos.push(`${order.pmName}<${order.pmEmail}>`);

    await sendMail({
        to: tos.join(','),
        subject: `【动态】日志更新 ${order.orderNo}【${order.project}】-${order.details}`,
        html: `
        <div style="white-space: pre-line;" >
            ${body.value}
        </div>
        <br/><br/><br/>
        <table border="1" cellspacing="0" cellpadding="5">
            <tr>
                <td style="width: 100px;">订单编号</td>
                <td>${order.orderNo}</td>
            </tr>
            <tr>
                <td>项目名称</td>
                <td>${order.project}</td>
            </tr>
            <tr>
                <td>承接类型</td>
                <td>${order.undertakingType}</td>
            </tr>
            <tr>
                <td>订单明细</td>
                <td>${order.details}</td>
            </tr>
            <tr>
                <td>计划开始时间</td>
                <td>${moment(order.planStartTime).format('YYYY-MM-DD')}</td>
            </tr>
            <tr>
                <td>计划完成时间</td>
                <td>${moment(order.produceCompletionTime).format('YYYY-MM-DD')}</td>
            </tr>
        </table>
        `
    })
}